package ch.sv7.tool.dbmanager.db.ant;

import org.apache.tools.ant.BuildException;

import ch.sv7.tool.dbmanager.DbManagerException;
import ch.sv7.tool.dbmanager.db.DatabaseSchema;
import ch.sv7.tool.dbmanager.db.Manager;
import ch.sv7.tool.dbmanager.db.TableReader;
import ch.sv7.tool.dbmanager.db.TableWriter;
import ch.sv7.tool.dbmanager.db.sql.SQLFullTableReader;
import ch.sv7.tool.dbmanager.db.xml.StringXmlTableWriter;

public class Sql2XmlTask extends TablesSqlTask {

	public void execute() throws BuildException {
		try {
			java.sql.Connection conn = getConnection();
			try {
				TableReader reader = new SQLFullTableReader(conn);
				TableWriter writer = new StringXmlTableWriter(getDirectory(), getSchema(),
						getFilePattern(), isFileZipped(), getEncoding());
				DatabaseSchema dbSchema = getDatabaseSchema(conn, getTables());
				Manager.copy(reader, writer, dbSchema, getTables());
			} catch (DbManagerException e) {
				throw new BuildException(e, getLocation());
			} catch (Exception e) {
				e.printStackTrace();
				throw new BuildException(e, getLocation());
			} finally {
				closeConnection(conn);
			}
		} catch (DbManagerException e) {
			throw new BuildException(e, getLocation());
		}
	}
}
